//
//  MGCircularProgress.m
//  Mango
//
//  Created by 胡超 on 2016/11/26.
//  Copyright © 2016年 胡超. All rights reserved.
//

#import "MGCircularProgress.h"

@interface MGCircularProgress () {
    CGFloat _startAngle;
    CGFloat _endAngle;
    
    NSTimer *_timer;
    NSTimeInterval _tInterval;
    NSTimeInterval _tPass;
}

@end

@implementation MGCircularProgress

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        self.backgroundColor = UIColor.clearColor;
        _barWidth = 2.0f;
        _progressTintColor = [UIColor darkGrayColor];
        _trackTintColor = [UIColor redColor];
        _startAngle = 1.5 * M_PI;
        _endAngle = _startAngle;
        
        _tInterval = 0.05;
        _tPass = 0.0;
    }
    return self;
}

// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
    UIBezierPath *circle = [UIBezierPath bezierPath];
    [circle addArcWithCenter:CGPointMake(rect.size.width / 2, rect.size.height / 2)
                      radius:(rect.size.width/2)-_barWidth/2
                  startAngle:0
                    endAngle:2 * M_PI
                   clockwise:YES];
    [circle setLineWidth:_barWidth];
    [_progressTintColor setStroke];
    [circle stroke];
    
    UIBezierPath *progress = [UIBezierPath bezierPath];
    [progress addArcWithCenter:CGPointMake(rect.size.width / 2, rect.size.height / 2)
                        radius:(rect.size.width/2)-_barWidth/2
                    startAngle:_startAngle
                      endAngle:_endAngle
                     clockwise:YES];
    [progress setLineWidth:_barWidth];
    [_trackTintColor setStroke];
    [progress stroke];
}

- (void)setProgress:(float)progress {
    _progress = progress;
    _endAngle = (progress * 2 * M_PI) + (1.5 * M_PI);
    
    [self setNeedsDisplay];
}

#pragma mark - CountDown

- (void)startCountdown {
    _tPass = 0.0;
    if (_timer == nil) {
        _timer = [NSTimer scheduledTimerWithTimeInterval:_tInterval target:self selector:@selector(updateProgress) userInfo:nil repeats:YES];
        [NSRunLoop.mainRunLoop addTimer:_timer forMode:NSRunLoopCommonModes];
    }
}

- (void)stopCountdown {
    [_timer invalidate];
    _timer = nil;
}

- (void)updateProgress {
    _tPass += _tInterval;
    self.progress = _tPass/self.countDownDuration;
    
    if (_tPass >= self.countDownDuration) {
        [self stopCountdown];
        if ([self.delegate respondsToSelector:@selector(circularProgressDidCountDownFinish:)]) {
            [self.delegate circularProgressDidCountDownFinish:self];
        }
    }
}

@end
